﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace Client
{
    public class ClientService
    {
        private int linkCount;
        private string ip;
        private int port;
        private int initCount;
        public ClientService(int _linkCount,int _initCount,string _ip,int _port)
        {
            linkCount = _linkCount;
            ip = _ip;
            port = _port;
            initCount=_initCount;
        }

        public void OpenClient()
        {
            for (int i = 0; i < initCount; i++)
            {
                var client = new TcpClient(ip, port);
                if (client.Connected)
                {
                    var socket = client.Client;
                    Thread cth = new Thread(() => Client(socket));
                    cth.Start();
                    socket.Send(Encoding.UTF8.GetBytes(PublicData.PackageData));
                    Thread.Sleep(500);
                }
                else {
                    PublicData.Error++;
                }
            }
        }

        public void AddClient(int count)
        {
            for (int i = 0; i < count; i++)
            {
                var client = new TcpClient(ip, port);
                if (client.Connected)
                {
                    var socket = client.Client;
                    Thread cth = new Thread(() => Client(socket));
                    cth.Start();
                    socket.Send(Encoding.UTF8.GetBytes(PublicData.PackageData));
                    Thread.Sleep(500);
                }
                else
                {
                    PublicData.Error++;
                }
            }
        }

        public void Client(Socket socket)
        {
            while (true)
            {
                var s = socket.Available;
                if (s > 0)
                {
                    try
                    {
                        byte[]buffer=new byte[s];
                        socket.Receive(buffer);
                        socket.Send(buffer);
                    }
                    catch (Exception )
                    {
                        PublicData.Error++;
                    }
                }
            }
        }
    }
}
